import { getSaleList, getTalkingBySaleId, userSend } from '@/services/conversation';
import { colorStr, getQueryParams } from '@/utils/utils';
import { useWebSocket } from 'ahooks';
import { Avatar, Button, Input, message, Modal } from 'antd';
import Picker from 'emoji-picker-react';
import moment from 'moment';
import { useCallback, useEffect, useState } from 'react';
import styles from './index.less';

interface Props {
  color: string;
  visible: boolean;
  acceptid?: string;
  onCancel: () => void;
}

const ConversationManage: React.FC<Props> = ({ color, visible, onCancel }) => {
  const { TextArea } = Input;
  const qs = getQueryParams();
  let sendId = qs.id;
  const [inputValue, setInputValue] = useState<string>('');
  const [test, setTest] = useState<number>(0);
  const [saleList, setSaleList] = useState<any[]>([]);
  // const [talkingRecord, setTalkingRecord] = useState<any[]>([]);
  const [saleName, setSaleName] = useState<string>('');
  const [saleId, setSaleId] = useState<string>('');
  const [emojiModal, setEmojiModal] = useState<boolean>(false);
  const [rightSent, setRightSent] = useState<any[]>([]);

  const getTalkingByUserID = useCallback(async () => {
    await getTalkingBySaleId({ saleId: saleId, userId: qs.id }).then((res) => {
      setRightSent(res);
      setTest(res.length);
    });
  }, [qs.id, saleId]);

  useEffect(() => {
    if (visible) {
      getTalkingByUserID();
    }
  }, [getTalkingByUserID, visible]);

  const getSale = useCallback(async () => {
    await getSaleList({ userId: qs.id }).then((res) => {
      if (res.length !== 0) {
        setSaleList(res);
        setSaleName(res[0].nickName);
        setSaleId(res[0].saleId);
      }
    });
  }, [qs.id]);

  useEffect(() => {
    getSale();
  }, [getSale]);

  const { sendMessage, latestMessage } = useWebSocket(`ws://localhost:3001/?userId=${sendId}`, {
    onOpen: () => {
      console.log('连接成功');
    },
    onClose: () => {
      onCancel();
      console.log('关闭成功');
    },
  });
  const send = () => {
    {
      sendMessage &&
        sendMessage(
          JSON.stringify({ userId: saleId, message: `${sendId}给${saleId}发送了${inputValue}` }),
        );
    }
  };

  useEffect(() => {
    if (latestMessage !== undefined) {
      getTalkingByUserID();
    }
  }, [getTalkingByUserID, latestMessage]);

  const preventBubble = function (e: any) {
    e.preventDefault();
  };
  const onEmojiClick = (event: any) => {
    setInputValue(`${inputValue}${event.emoji}`);
    setEmojiModal(false);
  };

  const sendBtn = async () => {
    if (inputValue != '') {
      send();
      await userSend({ userId: qs.id, saleId: saleId, userTalking: inputValue }).then(() => {
        getTalkingByUserID();
        setInputValue('');
      });
    } else {
      message.error('请输入消息');
    }
  };

  const scrollToBottom = () => {
    document.getElementById('box')?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [test]);

  const onChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    let value = e.target.value;
    setInputValue(value);
  };

  return (
    <Modal
      title={`和${saleName}的聊天`}
      className={styles.container}
      open={visible}
      onCancel={onCancel}
      width={888}
      footer={[]}
    >
      <div className={styles.talkWindow}>
        <div className={styles.usesrTable}>
          <div className={styles.topTable}>聊天列表：</div>
          {saleList.map((item) => [
            <div
              key={item.saleId}
              className={saleId === item.saleId ? styles.selectedInfo : styles.userInfo}
              onClick={() => {
                setSaleId(item.saleId);
              }}
            >
              {/* <Badge count={item.count}> */}
              {item.nickName}
              {/* </Badge> */}
            </div>,
          ])}
        </div>
        <div className={styles.leftBox}>
          {emojiModal && (
            <div className={styles.emojiModal}>
              <Picker onEmojiClick={onEmojiClick} />
            </div>
          )}
          <div className={styles.recording}>
            {rightSent.map((item: any) => (
              <div
                key={item.id}
                className={item.userTalking !== '' ? styles.rightSent : styles.leftSent}
              >
                {item.userTalking !== '' ? (
                  <Avatar
                    size={40}
                    style={{
                      margin: '0 8px',
                      cursor: 'context-menu',
                    }}
                    src={
                      <img
                        src={`http://localhost:8090/dyh/upload_images/user/四季养生.jpg`}
                        alt=""
                      />
                    }
                  />
                ) : (
                  <Avatar
                    size={40}
                    style={{
                      margin: '0 8px',
                      cursor: 'context-menu',
                    }}
                    src={
                      <img
                        src={`http://localhost:8090/dyh/upload_images/business/${item.avatar}`}
                        alt=""
                      />
                    }
                  />
                )}
                <div>
                  <div className={styles.someInfor}>
                    {moment(Number(item.timeSaid)).format('YYYY-MM-DD HH:mm:ss')}&emsp;
                    {item.userTalking !== '' ? qs.nickname : item.nickName}
                  </div>
                  <div className={styles.rightRecording}>
                    <div
                      className={styles.talking}
                      style={{
                        background: item.userTalking !== '' ? colorStr(2) : '#fff',
                      }}
                    >{`${item.userTalking === '' ? item.shopTalking : item.userTalking}`}</div>
                  </div>
                </div>
              </div>
            ))}
            <div id="box" />
          </div>
          <div className={styles.inputSend}>
            <TextArea
              maxLength={500}
              value={inputValue}
              onChange={onChange}
              placeholder={'请输入消息，按Enter键 或 点击发送按钮发送'}
              onPressEnter={(e) => {
                preventBubble(e);
                scrollToBottom();
                sendBtn();
              }}
              bordered={false}
              autoSize={{ minRows: 6, maxRows: 6 }}
              showCount
            />
            <Button style={{ backgroundColor: color }} className={styles.sendBtn} onClick={sendBtn}>
              发送
            </Button>
            <div className={styles.emoji}>
              <img
                src="https://gw.alicdn.com/imgextra/i2/O1CN01NMGMUe1G7qqwWm4Ud_!!6000000000576-55-tps-18-18.svg"
                alt={''}
                onClick={() => {
                  setEmojiModal(true);
                }}
              />
            </div>
          </div>
        </div>
      </div>
    </Modal>
  );
};

export default ConversationManage;
